package com.izhengyin.gateway.webagent;

import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;

public class SpringMvcApiDefineProvider implements ApiDefineProvider {
    @Override
    public List<GatewayWebApiDefine> getApiDefines(ApplicationContext context) {
        RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping)context.getBean("requestMappingHandlerMapping");
        List<GatewayWebApiDefine> gatewayWebApiDefines = new ArrayList<>();
        requestMappingHandlerMapping.getHandlerMethods()
                .forEach((requestMappingInfo, handlerMethod) -> {
                    GatewayWebApiDefine gatewayWebApiDefine = new GatewayWebApiDefine();
                    gatewayWebApiDefine.setName(Optional.ofNullable(requestMappingInfo.getName()).orElse(""));
                    gatewayWebApiDefine.setMethod(handlerMethod.toString());
                    gatewayWebApiDefine.setHttpMethod(requestMappingInfo.getMethodsCondition().getMethods());
                    Set<String> pathPatterns = requestMappingInfo.getPatternsCondition().getPatterns();
                    gatewayWebApiDefine.setPathPatterns(pathPatterns);
                    gatewayWebApiDefine.setMappingInfo(requestMappingInfo.toString());
                    gatewayWebApiDefines.add(gatewayWebApiDefine);
                });
        return gatewayWebApiDefines;
    }
}
